package com.crl.factory.pool
{
	import com.crl.factory.IFactory;

	/**
	 * 对像池; 
	 * @author crl
	 * 
	 */	
	public class ObjectPool implements IPool
	{
		protected var storage:Vector.<IRecycleable>;
		protected var poolSize:int;
		
		protected var size:int;
		private var factory:IFactory
		public function ObjectPool(factory:IFactory,poolSize:int=1)
		{
			this.factory=factory;
			this.poolSize=poolSize;
			
			storage=new Vector.<IRecycleable>();
			
			size=0;
		}
		
		public function get():IRecycleable
		{
			var instance:IRecycleable;
			if(storage.length){
				instance=storage.shift();
				instance.awake();
				
				size--;
			}else{
				instance=factory.newInstance();
				instance.setPool(this);
			}
			
			return instance;
		}
		
		public function recycle(item:IRecycleable):void
		{
			if(storage.length<poolSize){
				item.sleep();
				storage.push(item);
				
				size++;
			}else{
				item.setPool(null);
				item.dispose();
			}
		}
		
		public function clear():void
		{
			for each(var instance:IRecycleable in storage){
				instance.setPool(null);
				instance.dispose();
			}
			storage.splice(0,storage.length);
			size=0;
		}
	}
}